import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.username) { // 持久化可以解决用户信息，左侧菜单路由显示刷新问题，但是router里面的路由实际已经没了，就是左侧菜单路由能显示，内部跳转路由没了，所以每次刷新都要重新获取信息
        // 调用获取用户信息接口
        await store.dispatch('user/getUserInfo')
        next(to.fullPath) // 相当于多做一次跳转 to.path带参数重定向没铺好的404页面
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
